package com.qd.system.importexcel.station;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.domain.entity.station.StationSetDTO;
import com.qd.common.sys.enums.BaseTableEnum;
import com.qd.system.model.StationSet;
import com.qd.system.service.dict.ExcelValidateUtil;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.station.StationSetService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 岗位职责,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
@RequiredArgsConstructor
public class StationSetImportHandler {

    private final StationSetService stationSetService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;
    private final ExcelValidateUtil excelValidateUtil = new ExcelValidateUtil();
    private final LocalDateTime now = LocalDateTime.now();


    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<StationSetDTO>> rowList, List<BatchResult> results) {
        final List<StationSetDTO> stationSetList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> existsIds = existsIds(stationSetList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<StationSetDTO> excelRowMsg : rowList) {
                final StationSetDTO stationSetDTO = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = buildImportDTO(stationSetDTO);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<StationSet> addStationSetList = new ArrayList<>(size);
                final List<StationSet> updateStationSetList = new ArrayList<>(size);
                doProcessDictData(existsIds, stationSetList, addStationSetList, updateStationSetList);
                BatchResult.buildBatchResult(results, addStationSetList.size(), updateStationSetList.size());
                addStationSetList.clear();
                updateStationSetList.clear();
            }
        } finally {
            stationSetList.clear();
            existsIds.clear();
        }
    }

    /**
     * 保存数据
     *
     * @param existsIds            已经存在的数据库主键
     * @param stationSetList       excel行数据集合
     * @param addStationSetList    添加集合
     * @param updateStationSetList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<StationSetDTO> stationSetList, List<StationSet> addStationSetList, List<StationSet> updateStationSetList) {
        stationSetList.forEach(stationSetDTO -> {
            final StationSet stationSet = stationSetService.dtoToModel(stationSetDTO);
            stationSetService.clearCache(stationSet);
            if (MbUtil.isExistInCollection(existsIds, stationSetDTO.getStationId())) {
                stationSet.setAddTime(null);
                stationSet.setUpdateTime(now);
                updateStationSetList.add(stationSet);
            } else {
                stationSet.setAddTime(now);
                stationSet.setUpdateTime(null);
                addStationSetList.add(stationSet);
            }
        });
        if (!addStationSetList.isEmpty()) {
            stationSetService.saveBatch(addStationSetList);
        }
        if (!updateStationSetList.isEmpty()) {
            stationSetService.updateBatchIds(updateStationSetList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param stationSetList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<StationSetDTO> stationSetList) {
        final List<String> ids = stationSetList.stream().map(StationSetDTO::getStationId).collect(toList());
        final List<String> existsIds = stationSetService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入验证
     *
     * @param stationSetDTO 单个excel行数据
     * @return 异常信息
     */
    private List<String> buildImportDTO(StationSetDTO stationSetDTO) {
        final List<String> errors = new ArrayList<>();
        //验证信息，自己编写
        final String enable = excelValidateUtil.isValidBase(stationSetDTO.getEnableDisplay(), BaseTableEnum.SF, errors);
        if (StringUtils.hasLength(enable)) {
            stationSetDTO.setEnable(enable);
        }
        importValidate(stationSetDTO, errors);
        return errors;
    }

    /**
     * 导入实体验证
     *
     * @param stationSetDTO 单个excel行数据
     * @param errors        异常信息存储
     */
    private void importValidate(StationSetDTO stationSetDTO, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(stationSetDTO, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}